package com.JobWebGem.system.controller;

import com.JobWebGem.system.annotation.AuthCheck;
import com.JobWebGem.system.common.BaseResponse;
import com.JobWebGem.system.common.DeleteRequest;
import com.JobWebGem.system.common.ErrorCode;
import com.JobWebGem.system.common.ResultUtils;
import com.JobWebGem.system.constant.UserConstant;
import com.JobWebGem.system.exception.BusinessException;
import com.JobWebGem.system.exception.ThrowUtils;
import com.JobWebGem.system.model.dto.hr.HrAddRequest;
import com.JobWebGem.system.model.dto.hr.HrQueryRequest;
import com.JobWebGem.system.model.dto.hr.HrUpdateRequest;
import com.JobWebGem.system.model.entity.Company;
import com.JobWebGem.system.model.entity.Hr;
import com.JobWebGem.system.model.entity.User;
import com.JobWebGem.system.model.vo.HrVO;
import com.JobWebGem.system.model.vo.LoginUserVO;
import com.JobWebGem.system.service.CompanyService;
import com.JobWebGem.system.service.HrService;
import com.JobWebGem.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Hr接口
 *
 * @author renli
 */
@RestController
@RequestMapping("/hr")
@Slf4j
@Api(tags = "Hr接口")
public class HrController {

    @Resource
    private UserService userService;

    @Resource
    private CompanyService companyService;

    @Resource
    private HrService hrService;

    // region 增删改查

    /**
     * 创建HR
     *
     * @param hrAddRequest
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("创建HR（仅管理员）")
    public BaseResponse<Integer> addHr(@RequestBody HrAddRequest hrAddRequest) {
        if (hrAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        QueryWrapper<User> queryUser = new QueryWrapper<>();
        QueryWrapper<Company> queryCompany = new QueryWrapper<>();
        queryCompany.eq("name", hrAddRequest.getCompanyName());
        Company company = companyService.getOne(queryCompany);
        queryUser.eq("userName", hrAddRequest.getName());
        User user = userService.getOne(queryUser);
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        Hr hr = new Hr();
        try {
            BeanUtils.copyProperties(hrAddRequest, hr);
            if (hrAddRequest.getSex() == "女") {
                hr.setSex(1);
            } else {
                hr.setSex(0);
            }
            hr.setUserId(user.getId());
            hr.setName(user.getUserName());
            hr.setCompanyId(company.getId());
            hrService.save(hr);
            user.setUserRole(UserConstant.HR_ROLE);
            userService.updateById(user);

        } catch (Exception e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "保存信息失败");
        }
        return ResultUtils.success(hr.getId());
    }

    /**
     * 删除HR(仅管理员)
     *
     * @param deleteRequest
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "删除HR(仅管理员)")
    public BaseResponse<Boolean> deleteHr(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = hrService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除失败");
        return ResultUtils.success(result);
    }

    /**
     * 更新HR
     *
     * @param hrUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @ApiOperation(value = "更新HR")
    public BaseResponse<Boolean> updateHr(@RequestBody HrUpdateRequest hrUpdateRequest) {
        if (hrUpdateRequest == null || hrUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        QueryWrapper<Hr> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", hrUpdateRequest.getId());
        Hr hr = hrService.getOne(queryWrapper);
        ThrowUtils.throwIf(hr == null, ErrorCode.NOT_FOUND_ERROR, "HR不存在");
        if (hrUpdateRequest.getName() == null || hrUpdateRequest.getName().equals("")) {
            hrUpdateRequest.setName(hr.getName());
        }
        if (hrUpdateRequest.getSex() == null || hrUpdateRequest.getSex().equals("")) {
            if ("0".equals(hr.getSex())) {
                hrUpdateRequest.setSex("男");
            } else {
                hrUpdateRequest.setSex("女");
            }
        }
        if (hrUpdateRequest.getAge() == null || hrUpdateRequest.getAge().equals("")) {
            hrUpdateRequest.setAge(hr.getAge());
        }
        if (hrUpdateRequest.getPosition() == null || hrUpdateRequest.getPosition().equals("")) {
            hrUpdateRequest.setPosition(hr.getPosition());
        }

        Hr updateHr = new Hr();
        if (hrUpdateRequest.getSex() == "女") {
            hr.setSex(1);
        } else {
            hr.setSex(0);
        }
        BeanUtils.copyProperties(hrUpdateRequest, updateHr);
        boolean result = hrService.updateById(updateHr);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "更新失败");
        return ResultUtils.success(result);
    }

    /**
     * 分页获取所有Hr
     *
     * @param hrQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @ApiOperation(value = "分页获取所有Hr（所有人）")
    public BaseResponse<Page<HrVO>> listUserByPage(@RequestBody HrQueryRequest hrQueryRequest) {
        long current = hrQueryRequest.getCurrent() == 0 ? 1 : hrQueryRequest.getCurrent();
        long size = hrQueryRequest.getPageSize() == 0 ? 10 : hrQueryRequest.getPageSize();
        Page<HrVO> paramPage = new Page<>(current, size);
        Page<HrVO> hrPage = hrService.getHrQuery(paramPage, hrQueryRequest);
        return ResultUtils.success(hrPage);
    }

    // endregion
}
